package tools.utils;

import entity.Const;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class Common {

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 空字符串判断
     */
    public static boolean isNullString(String s) {
        return (s == null || s.length() <= 0) ? true : false;
    }

    // 该方法将你输入的字符串，通过md5加密，返回一个加密后的字符串
    public static String MD5Encrypt(String inStr) {

        MessageDigest md = null;
        String outStr = null;
        try {
            md = MessageDigest.getInstance("MD5"); // 可以选中其他的算法如SHA
            byte[] digest = md.digest(inStr.getBytes());
            // 返回的是byet[]，要转化为String存储比较方便
            outStr = bytetoString(digest);
        } catch (NoSuchAlgorithmException nsae) {
            nsae.printStackTrace();
        }
        return outStr;
    }

    public static String bytetoString(byte[] digest) {

        String str = "";
        String tempStr = "";
        for (int i = 1; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str = str + tempStr;
            }
        }
        return str.toLowerCase();
    }

    public static String generateToken(HashMap<String, Object> userMap) {

        String token = Jwts.builder()
                .setClaims(userMap)
                .setExpiration(new Date(new Date().getTime() + Const.JWT_EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, Const.JWT_KEY).compact();
        return Const.PRE_TOKEN + token;
    }

    public static int getPageNum(String page_num) {
        return Common.isNullString(page_num) ? Const.DEFAULT_PAGE_NUM : Integer.parseInt(page_num);
    }

    public static int getPageSize(String page_size) {
        return Common.isNullString(page_size) ? Const.DEFAULT_PAGE_SIZE : Integer.parseInt(page_size);
    }

    public static String getSysDate(String format) {
        if (Common.isNullString(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }
}
